package com.study.servlet;

import com.alibaba.fastjson.JSON;
import com.study.factory.BeanFactory;
import com.study.factory.ProxyFactory;
import com.study.pojo.Result;
import com.study.service.TransferService;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Qi XueSong
 */
@WebServlet(name="transferServlet",urlPatterns = "/transferServlet")
public class TransferServlet extends HttpServlet {

    //实例化service层对象，可以通过 IOC 的方式进行优化
    //private TransferService transferService = new TransferServiceImpl();

    // 修改为动态代理去调用
    //private final TransferService transferService = BeanFactory.getBean("transferService");

    // 首先从BeanFactory获取到proxyFactory代理工厂的实例化对象
    private final ProxyFactory proxyFactory = BeanFactory.getBean("proxyFactory");
    // 通过JDK动态代理获取到TransferService对象的代理对象
    private final TransferService transferService = proxyFactory.getJdkProxy(BeanFactory.getBean("transferService"));

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        //设置请求体的字符编码
        req.setCharacterEncoding("UTF-8");

        String fromCardNo = req.getParameter("fromCardNo");
        String toCardNo = req.getParameter("toCardNo");
        String moneyStr = req.getParameter("money");
        int money = Integer.parseInt(moneyStr);

        Result result = new Result();

        try {

            //调用service层方法
            transferService.transfer(fromCardNo,toCardNo,money);
            result.setStatus("200");
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus("201");
            result.setMessage(e.toString());
        }

        //响应
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().print(JSON.toJSONString(result));
    }
}
